<template>
  <view class="add-consultation bg-white px-4 box-border">
    <view>
      <up-form
        labelPosition="left"
        :model="form"
        :rules="rules"
        ref="uForm"
        labelWidth="75"
      >
        <up-form-item
          label="接收对象"
          borderBottom
          required
          prop="policeIds"
          @click="selectUser()"
        >
          <up-input
            v-model="form.policeUsers"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择咨询接收对象"
            border="none"
            color="#000000"
            inputAlign="right"
            placeholderStyle="{color: '#707070'}"
          ></up-input>
          <template #right>
            <up-icon name="arrow-right" color="#000000"></up-icon>
          </template>
        </up-form-item>
        <view class="evaluate-content">
          <up-form-item label="咨询内容" required prop="content">
            <textarea
              class="content-input"
              v-model="form.content"
              placeholder="可输入100字以内的咨询内容"
              placeholder-style="color:#dddddd"
              maxlength="-1"
            >
            <text class="absolute right-[10rpx] bottom-[4rpx] text-[24rpx] text-[#909193] bg-white px-[8rpx] py-[2rpx]">{{
                form.content.length
              }}/100</text>
          </textarea
            >
          </up-form-item>
        </view>
        <view class="flex flex-row justify-between items-center py-4">
          <text class="text-[29rpx] color-black">图片</text>
          <!-- <button class="btn-038AFE btn-normal mr-0">上传</button> -->
        </view>
        <!-- 图片列表 -->
        <view class="image-list">
          <up-upload
            :fileList="fileList"
            @afterRead="afterRead"
            @delete="deletePic"
            multiple
            :maxCount="10"
            :previewFullImage="true"
          ></up-upload>
        </view>
        <view class="text-[28rpx] text-[#8A8A8A] py-3"
          >（说明：请上传照片信息，最多支持上传10张）</view
        >
        <view class="bottom-line"></view>
      </up-form>
    </view>
    <button
      class="btn-0189FE h-[83rpx] leading-[83rpx] text-[33rpx] mt-[84rpx]"
      @click="onsubmit"
    >
      提 交
    </button>
    <up-gap height="50"></up-gap>
    <up-toast ref="uToastRef"></up-toast>
  </view>
</template>
<script setup lang="ts">
import { policeListByCommunityId } from "@/api/police";
import { addConsultation } from "@/api/consultation/index";
import { uploadFilePromise } from "@/utils/tools";
import { useUserInfoStore } from "@/stores/userInfo";
const userInfoStore = useUserInfoStore();

const uToastRef = <any>ref(null);
const formData = reactive({
  form: <any>{
    communityId: userInfoStore.crowdInfo.communityId,
    content: "",
    imgUrl: "",
    policeIds: <any>[],
    policeUsers: undefined,
  },
  rules: {
    policeIds: {
      type: "array",
      required: true,
      message: "请选择咨询接收对象",
      trigger: ["blur", "change"],
    },
    content: [
      {
        type: "string",
        required: true,
        message: "请填写咨询内容",
        trigger: ["blur", "change"],
      },
      {
        type: "string",
        max: 100,
        required: true,
        message: "请限制咨询内容在100字符内！",
        trigger: ["blur", "change"],
      },
    ],
  },
});

const { form, rules } = toRefs(formData);
const uForm = <any>ref(null);
const fileList = ref(<any>[]);

const selectUser = () => {
  uni.hideKeyboard(); // 隐藏键盘
  let timer = setTimeout(() => {
    uni.navigateTo({
      url: `/subPages/crowd/serviceEvaluation/selectUser?users=${form.value.policeIds.join(
        ","
      )}`,
    });
  }, 100);
};

// 删除图片
const deletePic = (event: any) => {
  fileList.value.splice(event.index, 1);
};

// 新增图片
const afterRead = async (event: any) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file);
  let fileListLen = fileList.value.length;
  lists.map((item) => {
    fileList.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url);
    let item = fileList.value[fileListLen];
    fileList.value.splice(fileListLen, 1, {
      ...item,
      status: "success",
      message: "",
      fileUrl: result.fileName,
    });
    fileListLen++;
  }
};

// 获取社区民警信息
const getPoliceList = () => {
  policeListByCommunityId({ communityId: userInfoStore.crowdInfo.communityId })
    .then((res: any) => {
      const { data } = res;
      let arr = data ?? [];
      if (arr.length === 1) {
        form.value.policeIds = [arr[0].policeUserId];
        form.value.policeUsers = [arr[0].userName + " " + arr[0].badgeNumber];
      }
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};

const onsubmit = () => {
  let arr = <any>[];
  if (fileList.value.length) {
    fileList.value.forEach((item: any) => {
      arr.push(item.fileUrl);
    });
  }
  form.value.imgUrl = arr.join(",");
  uForm.value
    .validate()
    .then((res: any) => {
      uni.showLoading({
        title: "提交中",
        mask: true,
      });
      addConsultation(form.value)
        .then((res: any) => {
          uni.hideLoading();
          uToastRef.value.show({
            type: "success",
            message: "提交成功",
          });
          let timer = setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
            clearTimeout(timer);
          }, 1500);
        })
        .catch((err: any) => {
          uni.hideLoading();
          uToastRef.value.show({
            type: "error",
            message: err,
          });
        });
    })
    .catch(() => {});
};

onShow(() => {
  uni.$on("updateServiceUser", (data) => {
    form.value.policeIds = data.selectUserIds;
    form.value.policeUsers = data.policeUsers;
  });
});

onUnload(() => {
  uni.hideKeyboard(); // 隐藏键盘
});

onLoad(() => {
  getPoliceList();
});

onReady(() => {
  uForm.value.setRules(rules.value);
});
</script>
<style lang="scss" scoped>
.add-consultation {
  .evaluate-content {
    ::v-deep .u-form-item__body {
      flex-direction: column !important;
    }
    ::v-deep .u-form-item__body__left {
      margin-bottom: 24rpx !important;
    }
  }
  .content-input {
    width: 100%;
    height: 360rpx;
    border: 0.5px solid #dadbde;
    border-radius: 8rpx;
    padding: 18rpx;
    font-size: 30rpx;
    color: #606266;
    box-sizing: border-box;
    position: relative;
  }

  .image-list {
    ::v-deep .u-upload__wrap__preview__image {
      width: 150rpx !important;
      height: 150rpx !important;
    }
  }
  .bottom-line {
    width: 100%;
    border-bottom: 1rpx solid #bbbbbb;
  }
}
</style>
